import os, sys
import traceback

import osg, osgGA, osgViewer
import threading
import wx

import Constants

class OSGHandler(osgGA.GUIEventHandler):
    
    def __init__(self, canvas, subcontroller):
        # store mouse x and y location for button press and move events
        self._mX = 0
        self._mY = 0
        
        self.canvas = canvas
        self.subcontroller = subcontroller
        
        self._selectedNode = 0
        self.wb = 0
        osgGA.GUIEventHandler.__init__(self)
        
        self.height = self.width = 0
        
    def handle(self, ea, aa, obj, nv):
        try:
            viewer = osgViewer.GUIActionAdapterToViewer(aa)
            if not viewer:
                return False
            eventtype = ea.getEventType()
            
            if eventtype == ea.RESIZE:
                self.width, self.height = self.canvas.GetClientSize()
                hudCamera = self.subcontroller.telepointerNode
                hudCamera.setProjectionMatrixAsOrtho2D(0, self.width, 0, self.height)
                print self.width, self.height

            if eventtype == ea.MOVE:
                self._mX = ea.getX()
                self._mY = ea.getY()
                
                if self.subcontroller.mode == Constants.MODE_TELEPOINTER:
                    # getXnormalized returns value between -1 and 1;
                    # we change them to be between 0 and 1
                    x = 0.5 + (ea.getXnormalized() * 0.5)
                    y = 0.5 + (ea.getYnormalized() * 0.5)
    
                    self.subcontroller.HandleLocalChange2dPointerPos( x, y )

            # only update the view if there is some dragging action
            if eventtype == ea.DRAG:
                if self.subcontroller.mode == Constants.MODE_STANDARD:
                    viewMatrix = viewer.getCameraManipulator().getMatrix()
                    self.subcontroller.HandleLocalViewChange( viewMatrix )
            
            if eventtype == ea.RELEASE:
                # check if mouse didn't drag since the last mouse button down
                if self._mX != ea.getX() or self._mY != ea.getY():
                    self.subcontroller.timerActive = True
                    timer = threading.Timer( 0.1, self.subcontroller.OnTimer )
                    timer.start()
                else:
                    self.subcontroller.timerActive = False
                    
            # deactivate timer
            if eventtype == ea.PUSH:
#                t = MyTrackballManipulator()
#                t.handle(ea, aa)
                self.subcontroller.timerActive = False

            
            if eventtype == ea.KEYDOWN:
                if ea.getKey() == 13: # enter key was pressed
                    self.subcontroller.changeMode()
                    
                if ea.getKey() == 100: # d
                    pass
                        
                if ea.getKey() == 101: # e
                    pass
                    
                if ea.getKey() == 102: # f
                    pass
#                    print 'adding pyramid'
#                    getController().rootNode.addChild( createTelepointerTest2() )
                    
                if ea.getKey() == 103: # g
                    pass
#                    print 'number of children:', self.subcontroller.rootNode.getNumChildren()
#                    print self.subcontroller.rootNode.getChild(1)
                    
                if ea.getKey() == 119: # w
                    if self.subcontroller.wireframe:
                        self.subcontroller.wireframe = False
                        polygonMode = osg.PolygonMode( osg.PolygonMode.FRONT_AND_BACK,
                                                       osg.PolygonMode.FILL )
                        self.subcontroller.modelNode.getOrCreateStateSet().setAttribute(
                                                                                polygonMode )
                    else:
                        self.subcontroller.wireframe = True
                        polygonMode = osg.PolygonMode( osg.PolygonMode.FRONT_AND_BACK,
                                                       osg.PolygonMode.LINE )
                        self.subcontroller.modelNode.getOrCreateStateSet().setAttribute(
                                                                                polygonMode )
    
    
            return False
        
        except:
            print "Unexpected error (" + str( sys.exc_info()[0] ) + '):', sys.exc_info()[1]
            traceback.print_tb(sys.exc_info()[2], None, sys.stdout)

class MyTrackballManipulator(osgGA.TrackballManipulator):
    def __init__(self):
        print 'MyTrackballManipulator is created'
        osgGA.TrackballManipulator.__init__(self)
        
    def handle(*args):
        print 'now!!!!!!!!!!!!!!'
        return osgGA.TrackballManipulator.handle(*args)